<?php 
    namespace Mark\Controller;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    use Zend\View\Model\JsonModel;
    use Mark\Entity\Like;
    use Mark\Entity\LikePhoto;
    use Mark\Entity\LikeVideo;
    use Activity\Entity\LikeActivity;

    use Mark\Component\LikeComponent;
    use Mark\Component\LikePhotoComponent;
    use Mark\Component\LikeVideoComponent;
    use Mark\Component\MarkPhotoComponent;
    use Mark\Component\MarkVideoComponent;

class LikeController extends AbstractActionController{
        protected $entityComponent;
        protected $likePhotoComponent;
        protected $likeVideoComponent;
        protected $markPhotoComponent;
        protected $markVideoComponent;
        protected $photoComponent;
        protected $videoComponent;
        protected $user;
        protected $nbMax = 20;

        protected $activityComponent;
        
        public function init(){
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            $this->entityComponent = new LikeComponent($this->em);
            $this->likePhotoComponent = new LikePhotoComponent($this->em);
            $this->likeVideoComponent = new LikeVideoComponent($this->em);
            $this->markPhotoComponent = new MarkPhotoComponent($this->em);
            $this->markVideoComponent = new MarkVideoComponent($this->em);
            $this->photoComponent = $this->getServiceLocator()->get('PhotoComponent');
            $this->videoComponent = $this->getServiceLocator()->get('VideoComponent');
            $this->activityComponent = $this->getServiceLocator()->get('ActivityComponent');
            $this->user = $this->identity();
        }

        public function addAction(){
            $this->init();
            if(false/*$this->request->isGet()*/){
            	$message = array();
            	return new ViewModel($message);
            }else{
                $subject = $this->getRequest()->getPost('subject', "video");
                $subjectId = $this->getRequest()->getPost('id', 21);
                if($this->user!=null && in_array($subject, array("photo", "video"))){
                    try{
                        //Checking first if the user have not already liked the item
                        if($subject=="photo"){
                            $photo = $this->photoComponent->get($subjectId);
                            if($photo==null){//La photo qu'on veut noter n'existe pas
                                $message = array(
                                		'result_code' => 'not_found',
                                		'id'=>$subjectId
                                );
                                return new JsonModel($message);
                            }
                            $likePhoto = $this->likePhotoComponent->getLikePhotoByUser($subjectId, $this->user->uid);
                            if($likePhoto!=null){
                                $message = array(
                                    "result_code"=>"ok",
                                	'success' => 'Photo alreday liked',
                                	'photo'=>$this->getPhotoJsonWithStats($photo)
                                );
                                return new JsonModel($message);
                            }
                        }else if($subject=="video"){
                            $video = $this->videoComponent->get($subjectId);
                            if($video==null){//La photo qu'on veut noter n'existe pas
                                $message = array(
                                		'result_code' => 'not_found',
                                		'id'=>$subjectId
                                );
                                return new JsonModel($message);
                            }
                            $likeVideo = $this->likeVideoComponent->getLikeVideoByUser($subjectId, $this->user->uid);
                            if($likeVideo!=null){
                                $message = array(
                                        "result_code"=>"ok",
                                    	'success' => 'Video alreday liked',
                                		'video'=>$this->getVideoJsonWithStats($video),
                                );
                                return new JsonModel($message);
                            }
                        }
                        
                        $like = new Like();
                        $like->user = $this->user;
                        $this->entityComponent->insert($like);
                        if($like!=null && $like->id!=null){
                        	$likeActivity = new LikeActivity();
                        	$likeActivity->like = $like;
                        	$likeActivity->date = $like->createdAt;
                        	$likeActivity->user = $like->user;
                        	$this->activityComponent->insert($likeActivity);//Saving the likeActivity
                        }
                        if($subject=="photo"){
                            $photo = $this->photoComponent->get($subjectId);
                            $likePhoto = new LikePhoto();
                            $likePhoto->like = $like;
                            $likePhoto->photo = $photo;
                            $this->likePhotoComponent->insert($likePhoto);
                            $message = array(
                                    "result_code"=>"success",
                                	'success' => 'Photo liked',
                                	'photo'=>$this->getPhotoJsonWithStats($photo)
                            );
                        }else if($subject=="video"){
                            $video = $this->videoComponent->get($subjectId);
                            $likeVideo = new LikeVideo();
                            $likeVideo->like = $like;
                            $likeVideo->video = $video;
                            $this->likeVideoComponent->insert($likeVideo);
                            $message = array(
                                    "result_code"=>"success",
                            		'success' => 'Video Liked. ',
                            		'video'=>$this->getVideoJsonWithStats($video),
                            );
                        }
                    
                    
                    } catch (\Exception $e) {
                         $message = array(
                         	'exception' => $e->getTraceAsString()
                         );
                    }
                }else{
                        $message = array(
                            "result_code"=>"not_connected",
                            'error' => 'Not connected'
                        );
                    }
                return new JsonModel($message);
            }
        }
        
        private function getPhotoJsonWithStats($photo){
            if($photo==null) return array();
            $photoJson =$photo->getJson();
            $stats = $this->markPhotoComponent->getStats2($photo->id);
            $nb_marks = $stats["nb"];
            $total_marks = $stats["total"];
            $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
            $myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($photo->id, $this->user->uid);
            $nbLikes = $this->likePhotoComponent->getNb($photo->id);
            $photoJson["nb_marks"] = $nb_marks;
            $photoJson["avg_marks"] = $avg_marks;
            $photoJson["i_like"] = ($myLike!=null);
            $photoJson["nb_likes"] = $nbLikes;
            return $photoJson;
        }
        
        private function getVideoJsonWithStats($video){
            if($video==null) return array();
            $videoJson =$video->getJson();
            $stats = $this->markVideoComponent->getStats2($video->id);
            $nb_marks = $stats["nb"];
            $total_marks = $stats["total"];
            $avg_marks = $nb_marks>0?(((int)($total_marks*10/$nb_marks))/10):0;
            $myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($video->id, $this->user->uid);
            $nbLikes = $this->likeVideoComponent->getNb($video->id);
            $videoJson["count_marks"] = $nb_marks;
            $videoJson["avg_marks"] = $avg_marks;
            $videoJson["i_like"] = ($myLike!=null);
            $videoJson["count_likes"] = $nbLikes;
            return $videoJson;
        }

        public function removeAction(){
            $this->init();
            if(false/*$this->request->isGet()*/){
            	$message = array();
            	return new ViewModel($message);
            }else{
                $subject = $this->getRequest()->getPost('subject', "photo");
                $subjectId = $this->getRequest()->getPost('id', 94);
                //var_dump($subjectId);
                if(in_array($subject, array("photo", "video"))){
                    try{
                        if($subject=="photo"){
                        	$likePhoto = $this->likePhotoComponent->getLikePhotoByUser($subjectId, $this->user->uid);
                        	if($likePhoto!=null){
                        	    $photo = $likePhoto->photo;
                        	    
                        	    $like = $likePhoto->like;
                        	    //var_dump($like);return new JsonModel(array());
                        	    $this->likePhotoComponent->deleteItem($likePhoto);
                        	    if($like!=null) $this->entityComponent->deleteItem($like);
                        		$message = array(
                        		    "result_code"=>"success",
                        			'success' => 'Like removed',
                        			'photo'=>$this->getPhotoJsonWithStats($photo),
                        		);
                        		return new JsonModel($message);
                        	}else{
                        	    $message = array(
                        	    		"result_code"=>"not_found",
                        	    		'error' => 'Like not found',
                        	    );
                        	}
                        }else if($subject=="video"){
                        	//TODO Implement the following method
                        	$likeVideo = $this->likeVideoComponent->getLikeVideoByUser($subjectId, $this->user->uid);
                        	if($likeVideo!=null){
                        	    $video = $likeVideo->video;
                        	    $like = $likeVideo->like;
                        	    $this->likeVideoComponent->deleteItem($likeVideo);
                        	    if($like!=null) $this->entityComponent->deleteItem($like);
                        		$message = array(
                        		    "result_code"=>"success",
                        			'success' => 'Like removed',
                        			'video'=>$this->getVideoJsonWithStats($video),
                        		);
                        		return new JsonModel($message);
                        	}
                        }
                    } catch (\Exception $e) {
                             $message = array(
                             	'exception' => $e->getTraceAsString()
                             );
                    }
                }
                return new JsonModel($message);
            }
        }

        


        public function photoLikesAction()
        {//List likes of a photo given as parameter
            $this->init();
            $id = (int)$this->params()->fromRoute('id', 0);
            $lastId = (int)$this->params()->fromRoute('offset', 0);
            $limit = (int)$this->params()->fromRoute('limit', '5');
            
            $list = $this->likePhotoComponent->listByPhoto2($id, $lastId, $limit);
            
            $likes = array();
            foreach ($list as $item){
                $likes[] = $item->getJson();
            }
            $stats = $this->likePhotoComponent->getStats2($id);
            $nb = $stats["nb"];
            $myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($id, $this->user->uid);
            return new JsonModel(
                array(
                    "likes"=>$likes,
                    "now"=>(new \DateTime("now"))->format("Y-m-d H:i:s"),
                    "count_likes"=>$nb,
                    "i_like"=>($myLike!=null)
                )
            );
        }
        
        public function videoLikesAction()
        {//List likes of a photo given as parameter
        $this->init();
        $id = (int)$this->params()->fromRoute('id', 0);
        $lastId = (int)$this->params()->fromRoute('offset', 0);
        $limit = (int)$this->params()->fromRoute('limit', '5');
        
        $list = $this->likeVideoComponent->listByVideo2($id, $lastId, $limit);
        
        $likes = array();
        foreach ($list as $item){
        	$likes[] = $item->getJson();
        }
        $stats = $this->likeVideoComponent->getStats2($id);
        $nb = $stats["nb"];
        $myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($id, $this->user->uid);
        return new JsonModel(
        		array(
        				"likes"=>$likes,
        				"now"=>(new \DateTime("now"))->format("Y-m-d H:i:s"),
        				"count_likes"=>$nb,
                        "i_like"=>($myLike!=null)
        		)
        );
        }
        
        
        public function likePhotoAction()
        {//Like a photo and send back the result that can be
            $this->init();
        	$post = $this->request->getPost();
        	$id = (int)$this->params()->fromPost('id');//The id of the photo to like
        	$user = $this->identity();
            
            $like = new Like();
            $like->user = $this->user;
            $this->entityComponent->insert($like);
            
            
            if($like!=null && $like->id!=null){
            	$likeActivity = new LikeActivity();
            	$likeActivity->like = $like;
            	$likeActivity->date = $like->createdAt;
            	$likeActivity->user = $like->user;
            	$this->activityComponent->insert($likeActivity);
            	
            	$photo = $this->photoComponent->get($id);
            	$likePhoto = new LikePhoto();
            	$likePhoto->like = $like;
            	$likePhoto->photo = $photo;
            	$this->likePhotoComponent->insert($likePhoto);
            	

            	$stats = $this->likePhotoComponent->getStats2($id);
            	$nb = $stats["nb"];
            	$avg = $nb>0?(((int)($stats["total"]*10/$nb))/10):0;
            	
            	$myLike = ($this->user==null)?null:$this->likePhotoComponent->getLikePhotoByUser($photo->id, $this->user->uid);
            	
            	$message = array(
            	    "result_code" => "success",
            		'success' => 'Photo Liked. ',
            	    "like"=>$likePhoto->getJson(),
                    "now"=>(new \DateTime("now"))->format("Y-m-d H:i:s"),
                    "count_likes"=>$nb,
            	    "i_like"=>($myLike!=null),
                    "avg_marks"=>$avg,
            	);
            	return new JsonModel($message);
            }
            return new JsonModel(array("error"=>"like failed","result_code"=>"error"));
    }

    public function likeVideoAction()
    {//Like a photo and send back the result that can be
    $this->init();
    $post = $this->request->getPost();
    $id = (int)$this->params()->fromPost('id');//The id of the photo to like
    $user = $this->identity();
    
    $like = new Like();
    $like->user = $this->user;
    $this->entityComponent->insert($like);
    
    
    if($like!=null && $like->id!=null){
    	$likeActivity = new LikeActivity();
    	$likeActivity->like = $like;
    	$likeActivity->date = $like->createdAt;
    	$likeActivity->user = $like->user;
    	$this->activityComponent->insert($likeActivity);
    	 
    	$video = $this->photoComponent->get($id);
    	$likeVideo = new LikeVideo();
    	$likeVideo->like = $like;
    	$likeVideo->video = $video;
    	$this->likeVideoComponent->insert($likeVideo);
    	 
    
    	$stats = $this->likeVideoComponent->getStats2($id);
    	$nb = $stats["nb"];
    	$avg = $nb>0?(((int)($stats["total"]*10/$nb))/10):0;
    	$myLike = ($this->user==null)?null:$this->likeVideoComponent->getLikeVideoByUser($video->id, $this->user->uid);
    	 
    	$message = array(
    			"result_code" => "success",
    			'success' => 'Photo Liked. ',
    			"like"=>$likeVideo->getJson(),
    			"now"=>(new \DateTime("now"))->format("Y-m-d H:i:s"),
    			"count_likes"=>$nb,
    	        "i_like"=>($myLike!=null),
    			"avg_marks"=>$avg,
    	);
    	return new JsonModel($message);
    }
    return new JsonModel(array("error"=>"like failed","result_code"=>"error"));
    }

    }
